﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：Wx.Sdk.Pay
*文件名： UsePay
*创建人： kingling
*创建时间：2018/10/6 18:19:43
*描述
*=======================================================================
*修改标记
*修改时间：2018/10/6 18:19:43
*修改人：kingling
*描述：
************************************************************************/

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Wx.Sdk.Pay;
using Wx.Sdk.Pay.Base;
using Wx.Sdk.Pay.Options;
using Wx.Sdk.Pay.Src;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class Pay
    {
        /// <summary>
        /// 使用微信支付，自行实现Notify
        /// </summary>
        /// <typeparam name="TNotify">Notify</typeparam>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddWeChatPay<TNotify>(this IServiceCollection services, IConfiguration configuration) where TNotify : Notify
        {
            services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddHttpClient();
            services.Configure<PayOption>(configuration);
            services.TryAddSingleton<INotify, TNotify>();
            services.TryAddSingleton<WxPay>();
            var path = configuration["sslpath"];
            var pass = configuration["sslpassword"];
            if (path.IsNull() || pass.IsNull())
            {
                return services;
            }
            var cert = Find(path, pass);
            services.AddHttpClient("crt").ConfigureHttpMessageHandlerBuilder((x) =>
            {
                var handler = new HttpClientHandler();

                handler.ClientCertificates.Add(cert);
                x.PrimaryHandler = handler;
            });
            return services;
        }
        /// <summary>
        /// 注册微信支付回调中间件
        /// </summary>
        /// <param name="app"></param>
        public static void AddWeChatPayMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<PayMiddleware>();
        }
        /// <summary>
        /// 查找证书
        /// </summary>
        /// <param name="sslpath"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        private static X509Certificate2 Find(string sslpath, string pass)
        {
            ////证书
            var path = AppDomain.CurrentDomain.BaseDirectory + sslpath;
            var certLoad = new X509Certificate2(path, pass);
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows) {
                //在个人区根据指纹查找证书
                var store = new X509Store("MY", StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var cert = store.Certificates.Find(X509FindType.FindByThumbprint, certLoad.Thumbprint, false)[0];
                return cert == null ? certLoad : cert;
            }
            return certLoad;
        }
    }
}
